package cn.justforchris.system.service.impl;




import cn.justforchris.system.domain.Role;

import cn.justforchris.system.mapper.RoleMapper;
import cn.justforchris.system.query.RoleQuery;
import cn.justforchris.system.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@CacheConfig(cacheNames = "Role")
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Override
    @Transactional
    @CacheEvict(key = "'RoleTree'")
    public void insertRole(Role role) {
        roleMapper.insertRole(role);
        List<Long> permissions = role.getPermissions();
        List<Long> menus = role.getMenus();
        if (permissions.size()>0) {
            roleMapper.addRolePermission(role);
        }
        if (menus.size()>0) {
            roleMapper.addRoleMenu(role);
        }

    }

    @Override
    @Transactional
    @CacheEvict(key = "'RoleTree'")
    public void updateRole(Role role) {
        roleMapper.updateRole(role);
        roleMapper.deleteRolePermission(role.getId());
        roleMapper.deleteRoleMenu(role.getId());
        List<Long> permissions = role.getPermissions();
        List<Long> menus = role.getMenus();
        if (permissions.size()>0) {
            roleMapper.addRolePermission(role);
        }
        if (menus.size()>0) {
            roleMapper.addRoleMenu(role);
        }
    }

    @Override
    @Transactional
    @CacheEvict(key = "'RoleTree'")
    public void deleteRole(Long id) {
        roleMapper.deleteRolePermission(id);
        roleMapper.deleteRoleMenu(id);
        roleMapper.deleteRole(id);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'RoleTree'")
    public void patchDelete(Long[] ids) {
        for (Long id : ids) {
            deleteRole(id);
        }
//        roleMapper.patchDelete(ids);
    }

    @Override
    public Role getRoleById(Long id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    public PageInfo<Role> queryPage(RoleQuery queryPage) {
        PageHelper.startPage(queryPage.getCurrentPage(),queryPage.getPageSize());
        List<Role> data = roleMapper.queryPage(queryPage);
        /*
        这里获取到的是符合传入参数currentpage和pagesize的数据,也就是说,如果不传pagesize就只有五条因为怕个size如果不传入的话就是5
        但是如果有pagesize传入就根据传入数据来
        */
        return new PageInfo<>(data);
        /*这里面就包含了pagehelper帮忙计算出来的total(总共多少条,和根据分页提取出的数据)*/
    }


}
